// Model for each ToDo item:
var TodoItemModel = Backbone.Model.extend({
  defaults: {
    todo: "",
    complete: false
  }
});

// Epoxy View for each ToDo item:
var TodoItemView = Backbone.Epoxy.View.extend({
  el:"<li><input type='checkbox'> <input type='text' class='todo'></li>",

  setterOptions: {save: true},

  bindings: {
    "input[type='text']": "value:todo,readonly:complete",
    "input[type='checkbox']": "checked:complete"
  },

  bindingHandlers: {
    readonly: function( $element, value ) {
        $element.prop( "readonly", !!value );
    }
  }
});

// Collection for ToDo items:
var TodosCollection = Backbone.Collection.extend({
  model: TodoItemModel,
  localStorage: new Backbone.LocalStorage("todos")
});

// Epoxy View for main ToDos app:
var TodoAppView = Backbone.Epoxy.View.extend({
  el: "#epoxy-todo-app",

  collection: new TodosCollection(),
  itemView: TodoItemView,

  initialize: function() {
    this.collection.fetch();
  },

  events: {
    "click .add": "onAdd",
    "click .cleanup": "onCleanup",
    "keydown .todo-add": "onEnter"
  },

  onEnter: function( evt ) {
    if ( evt.which == 13 ) this.onAdd();
  },

  onAdd: function() {
    var input = this.$(".todo-add");

    if ( input.val() ) {
        this.collection.create({todo: input.val()});
        input.val("");
    }
  },

  onCleanup: function() {
    _.invoke(this.collection.where({complete:true}), "destroy");
  }
});

var app = new TodoAppView();